<template>
  <el-card>
    <template #header>
      <h2>个人中心</h2>
    </template>

      <!-- 用户信息界面展示-->
      <el-card>
        <template>
        <el-upload :headers="local"
          action="http://127.0.0.1:3000/users/avatar"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <el-row v-if="avatar">
            <el-col :span="12">
              <el-avatar :size="50" :src="avatar"></el-avatar>
            </el-col>
          </el-row>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        </template>
        <el-divider></el-divider>
        <template>用户:{{personal.username}}
          <el-button @click="propChange('用户', 'username')">修改</el-button>
        </template>
        <el-divider></el-divider>
        <template>性别:{{["女","男"][personal.gender]}}
          <el-button @click="propChange('性别', 'gender')">修改</el-button>
        </template>
        <el-divider></el-divider>
        <template>手机:{{personal.phone}}
          <el-button @click="propChange('手机', 'phone')">修改</el-button>
        </template>
        <el-divider></el-divider>
        <template>邮箱:{{personal.email}}
          <el-button @click="propChange('邮箱', 'email')">修改</el-button>
        </template>
        <el-divider></el-divider>
        <template>
          <el-button @click="dialogPassword=true;">修改密码</el-button>
        </template>
        <el-divider></el-divider>
      </el-card>

    <!-- 用户信息修改 -->
    <el-dialog title="修改" :visible.sync="dialogVisible" width="500px">
      <el-form :model="editForm" ref="editForm" :rules="editRules" label-width="100px">
        <el-form-item :label="nameTitle" :prop="propTitle">
          <el-input v-model="editForm[propTitle]" v-if="propTitle!='gender'"></el-input>
          <el-radio-group v-if="propTitle==='gender'" v-model="editForm[propTitle]">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save(propTitle)">保存</el-button>
      </span>
    </el-dialog>
<!-- 用户密码修改 -->
    <el-dialog title="修改密码" :visible.sync="dialogPassword" width="500px">
      <el-form ref="passwordForm" :rules="editRulesPassword" :model="passwordForm"
      label-width="150px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input show-password v-model="passwordForm.oldPassword"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input show-password v-model="passwordForm.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input show-password v-model="passwordForm.confirmPassword"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="editPasswod">保存</el-button>
        <el-button @click="dialogPassword = false">取消</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { createNamespacedHelpers } from 'vuex';

const { mapActions, mapState } = createNamespacedHelpers('personal');

export default {
  data() {
    // 用户信息修改验证
    const validateUsername = async (rule, value, callback) => {
      const reg = /^\w{2,18}$/;
      if (reg.test(value)) {
        const { data } = await this.apis.usersExist({
          field: 'username',
          value,
        });
        if (!data) {
          callback();
        } else {
          callback(new Error('用户名已存在'));
        }
      } else {
        callback(new Error('用户名在2-18个字母和数字组合'));
      }
    };
    const editValidateUsername = (rule, value, callback) => {
      if (value === this.row.username) {
        callback();
      } else {
        validateUsername(rule, value, callback);
      }
    };

    const validatePhone = async (rule, value, callback) => {
      const reg = /^1[3456789]\d{9}$/;
      if (reg.test(value)) {
        const { data } = await this.apis.usersExist({
          field: 'phone',
          value,
        });
        if (!data) {
          callback();
        } else {
          callback(new Error('手机已存在'));
        }
      } else {
        callback(new Error('手机格式错误'));
      }
    };
    const editValidatePhone = (rule, value, callback) => {
      if (value === this.row.phone) {
        callback();
      } else {
        validatePhone(rule, value, callback);
      }
    };

    const validateEmail = async (rule, value, callback) => {
      const reg = /^\w{2,18}@\w{2,18}\.com$/;
      if (reg.test(value)) {
        const { data } = await this.apis.usersExist({
          field: 'email',
          value,
        });
        if (!data) {
          callback();
        } else {
          callback(new Error('邮箱已存在'));
        }
      } else {
        callback(new Error('邮箱格式错误'));
      }
    };
    const editValidateEmail = (rule, value, callback) => {
      if (value === this.row.email) {
        callback();
      } else {
        validateEmail(rule, value, callback);
      }
    };

    const validateConfirmPassword = (rule, value, callback) => {
      if (value === this.passwordForm.newPassword) {
        callback();
      } else {
        callback(new Error('两次密码不一致'));
      }
    };
    return {
      local: {
        authorization: localStorage.getItem('token'),
      },
      imageUrl: '',
      row: {},
      dialogVisible: false,
      dialogPassword: false,
      propTitle: '',
      nameTitle: '',
      editForm: {
        username: '',
        gender: 1,
        phone: '',
        email: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
      },
      // 用户信息修改验证规则
      editRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: editValidateUsername, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: editValidatePhone, trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: editValidateEmail, trigger: 'blur' },
        ],
      },
      editRulesPassword: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            min: 6, max: 18, message: '长度在6-18个字符', trigger: 'blur',
          },
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' },
        ],
      },
    };
  },
  computed: {
    ...mapState(['personal', 'avatar']),
  },
  created() {
    this.getPersonal();
  },
  methods: {
    // 头像修改
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    async beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/png' || 'image/jpg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    headPortrait() {

    },
    // 密码修改
    editPasswod() {
      this.$refs.passwordForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const data = {};
        data.oldPassword = this.passwordForm.oldPassword;
        data.newPassword = this.passwordForm.newPassword;
        await this.apis.editPersonalPassword(data).then(() => {
          this.$message('密码修改成功');
        }).catch(() => {
          this.$message.error('原密码错误');
        });
        this.dialogPassword = false;
        this.getPersonal();
      });
    },
    // 用户信息修改
    save(name) {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const data = {};
        if (this.editForm[name] !== this.row[name]) {
          data[name] = this.editForm[name];
        }
        await this.apis.editPersonal(data);
        this.dialogVisible = false;
        this.getPersonal();
      });
    },
    // 用户修改按钮
    propChange(nTitle, pTitle) {
      this.row[pTitle] = this.personal[pTitle];
      this.editForm[pTitle] = this.personal[pTitle];
      this.nameTitle = nTitle;
      this.propTitle = pTitle;
      this.dialogVisible = true;
    },
    ...mapActions(['getPersonal']),
  },
};
</script>
